package com.example.userlogin.service;

import com.example.userlogin.dto.UserProfileResponse;
import com.example.userlogin.entity.User;
import com.example.userlogin.exception.UserNotFoundException;
import com.example.userlogin.security.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户资料服务
 * 职责：处理用户资料相关操作
 */
@Service
public class UserProfileService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserAuditService userAuditService;

    /**
     * 获取当前用户资料
     */
    @Transactional(readOnly = true)
    public UserProfileResponse getCurrentUserProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        
        if (authentication == null || !(authentication.getPrincipal() instanceof UserDetailsImpl)) {
            throw new IllegalStateException("用户未认证");
        }

        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        return new UserProfileResponse(
            userDetails.getId(),
            userDetails.getUsername(),
            userDetails.getEmail()
        );
    }

    /**
     * 根据用户ID获取用户资料
     */
    @Transactional(readOnly = true)
    public UserProfileResponse getUserProfile(Long userId) {
        User user = userService.findById(userId);
        
        return new UserProfileResponse(
            user.getId(),
            user.getUsername(),
            user.getEmail()
        );
    }

    /**
     * 更新用户邮箱
     */
    @Transactional(rollbackFor = Exception.class)
    public UserProfileResponse updateUserEmail(Long userId, String newEmail) {
        User user = userService.findById(userId);
        String oldEmail = user.getEmail();
        
        // 检查新邮箱是否已被使用
        if (userService.existsByEmail(newEmail)) {
            throw new IllegalArgumentException("邮箱已被使用: " + newEmail);
        }
        
        user.setEmail(newEmail);
        User updatedUser = userService.updateUser(user);
        
        // 记录审计日志
        userAuditService.logUserUpdate(user.getUsername(), "email", oldEmail, newEmail);
        
        return new UserProfileResponse(
            updatedUser.getId(),
            updatedUser.getUsername(),
            updatedUser.getEmail()
        );
    }

    /**
     * 检查用户是否存在
     */
    @Transactional(readOnly = true)
    public boolean userExists(Long userId) {
        try {
            userService.findById(userId);
            return true;
        } catch (UserNotFoundException e) {
            return false;
        }
    }

    /**
     * 获取用户基本信息（用于显示）
     */
    @Transactional(readOnly = true)
    public UserBasicInfo getUserBasicInfo(Long userId) {
        User user = userService.findById(userId);
        return new UserBasicInfo(user.getId(), user.getUsername());
    }

    /**
     * 用户基本信息DTO
     */
    public static class UserBasicInfo {
        private Long id;
        private String username;

        public UserBasicInfo(Long id, String username) {
            this.id = id;
            this.username = username;
        }

        // Getters
        public Long getId() { return id; }
        public String getUsername() { return username; }
    }
}